package com.xmmj.baselibrary.base.dialog

import android.app.Dialog
import com.xmmj.baselibrary.base.activity.mvvm.IBaseView
import com.xmmj.baselibrary.widget.loading.LoadingDialog
import android.widget.TextView
import android.os.Bundle
import com.xmmj.baselibrary.R
import android.view.*
import android.widget.Button
import android.widget.Toast
import com.scwang.smart.refresh.layout.SmartRefreshLayout

/**
 * 实现公共UI操作的Dialog
 */
abstract class BaseDialog : RxDialog(), IBaseView {
    //Loading
    private var loadingDialog: LoadingDialog? = null

    //错误提示
    private var vBaseError: View? = null
    private var tvBaseError: TextView? = null
    private var btnBaseError: Button? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (getView() != null && vBaseError == null) {
            vBaseError = layoutInflater.inflate(R.layout.dialog_error, null)
            tvBaseError = vBaseError?.findViewById(R.id.tv_base_error)
            btnBaseError = vBaseError?.findViewById(R.id.btn_base_error)
            btnBaseError?.setOnClickListener { onRequest() }
            vBaseError?.visibility = View.GONE
            (getView()?.rootView as ViewGroup).addView(
                vBaseError,
                ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
        }

        onRequest()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val mDialog = super.onCreateDialog(savedInstanceState)
        //输入法允许弹出
        mDialog.window!!.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        mDialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

        //设置宽高
        val window = mDialog.window!!
        window.decorView.setPadding(0, 0, 0, 0)
        val wlp = window.attributes
        wlp.width = getWidth().toInt()
        wlp.height = getHeight().toInt()
        window.attributes = wlp

        //设置样式
        if (getStyle() > 0) {
            setStyle(STYLE_NO_TITLE, getStyle())
        }

        //设置动画
        if (getAnimations() > 0) {
            window.setWindowAnimations(getAnimations())
        }

        //设置位置
        if (isInBottom()) {
            window.setGravity(Gravity.BOTTOM)
        } else {
            window.setGravity(Gravity.CENTER)
        }

        //设置背景
        window.setBackgroundDrawableResource(getBackgroundDrawableResource())

        //设置可取消
        mDialog.setCancelable(isCancelable)
        mDialog.setCanceledOnTouchOutside(isCancelable)
        mDialog.setOnKeyListener { dialogInterface, keyCode, keyEvent ->
            if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
                if (isCancelable) {
                    dismissAllowingStateLoss()
                } else {
                    return@setOnKeyListener true
                }
            }
            false
        }
        return mDialog
    }

    /**
     * 显示Loading
     */
    override fun showLoading(cancelable: Boolean) {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog()
        }
        loadingDialog!!.isCancelable = cancelable
        loadingDialog!!.show(this)
    }

    /**
     * 隐藏Loading
     */
    override fun hideLoading() {
        if (loadingDialog != null) loadingDialog!!.dismiss()
    }

    /**
     * 吐司
     */
    override fun toast(msg: String?) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 重新登录
     */
    override fun onReLogin() {

    }

    /**
     * 发起请求
     */
    override fun onRequest() {
        if (vBaseError != null) {
            vBaseError!!.visibility = View.GONE
        }
    }

    /**
     * 显示错误提示
     */
    override fun showError(imageId: Int, errorText: String?, btnText: String?) {
        if (vBaseError != null) {
            vBaseError!!.visibility = View.VISIBLE
            tvBaseError!!.visibility = View.VISIBLE
            btnBaseError!!.visibility = View.VISIBLE
            tvBaseError!!.setCompoundDrawablesWithIntrinsicBounds(0, imageId, 0, 0)
            tvBaseError!!.text = errorText
            btnBaseError!!.text = btnText
        }
    }

    /**
     * 显示空提示
     */
    override fun showEmpty(isShow: Boolean, imageId: Int, hintText: String?) {
        if (vBaseError != null) {
            vBaseError!!.visibility = if (isShow) View.VISIBLE else View.GONE
            btnBaseError!!.visibility = View.GONE
            tvBaseError!!.setCompoundDrawablesWithIntrinsicBounds(0, imageId, 0, 0)
            tvBaseError!!.text = hintText
        }
    }

    /**
     * 结束刷新动画
     */
    override fun finishRefresh() {
        val refresh = view?.let { findView(it, SmartRefreshLayout::class.java) }
        refresh?.finishRefresh()
    }

    /**
     * 结束加载更多动画
     */
    override fun finishLoadMore(noMoreData: Boolean) {
        val refresh = view?.let { findView(it, SmartRefreshLayout::class.java) }
        if (noMoreData) {
            refresh?.finishLoadMoreWithNoMoreData()
        } else {
            refresh?.setNoMoreData(false)
            refresh?.finishLoadMore()
        }
    }

    /**
     * 遍历布局查找指定类型的控件
     */
    private fun <T : View?> findView(view: View, cls: Class<T>): T? {
        if (view.javaClass == cls) {
            return view as T
        }
        if (view is ViewGroup) {
            for (index in 0..view.childCount) {
                if (view.getChildAt(index) != null) {
                    if (findView(view.getChildAt(index), cls) != null) {
                        return findView(view.getChildAt(index), cls)
                    }
                }
            }
        }
        return null
    }

    /**
     * 设置样式
     */
    open fun getStyle(): Int {
        return if (isInBottom()) R.style.BaseBottomDialogStyle else R.style.BaseDialogStyle
    }

    /**
     * 设置动画
     */
    open fun getAnimations(): Int {
        return if (isInBottom()) R.style.BaseBottomDialogSheetAnimation else R.style.BaseDialogAnimation
    }

    /**
     * 设置背景
     */
    open fun getBackgroundDrawableResource(): Int {
        return R.color.color_transparent
    }

    /**
     * 是否至于屏幕底部
     */
    open fun isInBottom(): Boolean {
        return false
    }

    /**
     * 是否显示中
     */
    open fun isShowing(): Boolean {
        return dialog != null && dialog!!.isShowing
    }

    /**
     * 需重写来设置对话框的宽度
     */
    abstract fun getWidth(): Float

    /**
     * 需重写来设置对话框的高度
     */
    abstract fun getHeight(): Float
}